package com.mzy.xmyx.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzy.xmyx.common.exception.XmyxException;
import com.mzy.xmyx.common.result.ResultCodeEnum;
import com.mzy.xmyx.model.sys.RegionWare;
import com.mzy.xmyx.sys.mapper.RegionWareMapper;
import com.mzy.xmyx.sys.service.RegionWareService;
import com.mzy.xmyx.vo.product.WareQueryVo;
import com.mzy.xmyx.vo.sys.RegionWareQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 城市仓库关联表 服务实现类
 * </p>
 *
 * @author mzy
 * @since 2023-11-29
 */
@Service
public class RegionWareServiceImpl extends ServiceImpl<RegionWareMapper, RegionWare> implements RegionWareService {

    @Autowired
    private RegionWareMapper regionWareMapper;

    @Override
    public IPage<RegionWare> selectPage(Integer page, Integer limit, RegionWareQueryVo regionWareQueryVo) {

        LambdaQueryWrapper<RegionWare> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(regionWareQueryVo.getKeyword())) {
            // 根据区域名称或仓库名称查询
            queryWrapper.like(RegionWare::getRegionName, regionWareQueryVo.getKeyword())
                    .or()
                    .like(RegionWare::getWareName, regionWareQueryVo.getKeyword());
        }

        Page<RegionWare> regionWarePage = regionWareMapper.selectPage(new Page<>(page, limit), queryWrapper);
        return regionWarePage;
    }

    @Override
    public Boolean batchRemove(List<Long> idList) {

        int row = regionWareMapper.deleteBatchIds(idList);
        return row > 0;
    }

    @Override
    public Boolean saveRegionWare(RegionWare regionWare) {

        // 判断是否已经添加过了
        LambdaQueryWrapper<RegionWare> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(RegionWare::getRegionId, regionWare.getRegionId());
        Integer count = regionWareMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new XmyxException(ResultCodeEnum.REGION_OPEN);
        }

        int row = regionWareMapper.insert(regionWare);
        return row > 0;

    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        RegionWare regionWare = regionWareMapper.selectById(id);
        regionWare.setStatus(status);
        int row = regionWareMapper.updateById(regionWare);
        return row > 0;
    }
}
